package com.lb.shopguide.ui.fragment.guide.recommend;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterOrderRecList;
import com.lb.shopguide.base.BasePageFragment;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.order.OrderListRecBean;
import com.lb.shopguide.entity.order.OrderTypeBean;
import com.lb.shopguide.event.guide.CloseOrderEvent;
import com.lb.shopguide.event.guide.OrderChangeEvent;
import com.lb.shopguide.event.guide.SendGoodsEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.fragment.guide.order.FragmentOrderDetail;
import com.lb.shopguide.ui.fragment.guide.order.FragmentOrderManager;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import okhttp3.RequestBody;

/**
 * Created by kang on 2017/6/3.
 */

public class FragmentOrderRecList extends BasePageFragment implements BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private AdapterOrderRecList mAdapterOrderList;
    private List<OrderListRecBean> mOrderBeanList;
    private OrderTypeBean mOrderTypeBean;


    public static FragmentOrderRecList newInstance(OrderTypeBean bean) {
        FragmentOrderRecList fragmentOrderList = new FragmentOrderRecList();
        Bundle bundle = new Bundle();
        bundle.putSerializable(AppConstant.ORDER_TYPE_BEAN, bean);
        fragmentOrderList.setArguments(bundle);
        return fragmentOrderList;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_order_rec_list;
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        mOrderBeanList = new ArrayList<>();
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.ORDER_TYPE_BEAN)) {
            mOrderTypeBean = (OrderTypeBean) bundle.getSerializable(AppConstant.ORDER_TYPE_BEAN);
        }
        sendRequestForPageData();
    }

    @Override
    public void initView() {
        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view, (ViewGroup) mRecyclerView.getParent(), false);
        TextView tvEmpty = noDataView.findViewById(R.id.tv_empty);
        switch (mOrderTypeBean.getTypeCode()) {
            case AppConstant.ORDER_STATUS_ALL_REC:
                tvEmpty.setText("暂时没有订单，赶快去下订单吧");
                break;
            case AppConstant.ORDER_STATUS_NO_DELIVER_REC:
                tvEmpty.setText("暂时没有待发货订单，赶快去下订单吧");
                break;
            case AppConstant.ORDER_STATUS_NO_RECEIVE_REC:
                tvEmpty.setText("暂时没有待收货订单，赶快去下订单吧");
                break;
            case AppConstant.ORDER_STATUS_CLOSED_REC:
                tvEmpty.setText("暂时没有已关闭订单，赶快去下订单吧");
                break;
            case AppConstant.ORDER_STATUS_FINISHED_REC:
                tvEmpty.setText("暂时没有已完成订单，赶快去下订单吧");
                break;
            case AppConstant.ORDER_STATUS_AFTER_SALE_REC:
                tvEmpty.setText("暂时没有售后订单，赶快去下订单吧");
                break;
            default:
                tvEmpty.setText("暂时没有订单，赶快去下订单吧");
                break;
        }
        errorView = LayoutInflater.from(mContext).inflate(R.layout.layout_error_view, (ViewGroup) mRecyclerView.getParent(), false);
        noDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });


        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        mAdapterOrderList = new AdapterOrderRecList(R.layout.item_rec_order_list, mOrderBeanList);
        mRecyclerView.setAdapter(mAdapterOrderList);
        mAdapterOrderList.setOnLoadMoreListener(this, mRecyclerView);
        mAdapterOrderList.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mOrderBeanList.size() > position) {

                }
            }
        });
        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).paintProvider(mAdapterOrderList).build());
//        mAdapterOrderList.setOnActionClickListener(mOnActionClickListener);

    }

    @Override
    public void finishRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
        mAdapterOrderList.loadMoreComplete();
    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }

    @Override
    public String getPageTag() {
        return FragmentOrderRecList.class.getName();
    }

    private void sendRequestCloseOrder(String orderNum) {
        HashMap hashMap = new HashMap();
        hashMap.put("orderNum", orderNum);
        RequestBody body = BizUtil.getBodyFromMap(hashMap);
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                    EventBus.getDefault().post(new CloseOrderEvent());
                    ToastUtils.showShort("关闭订单成功");
                    pop();
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        };
        ApiMethodGuide.closeOrder(new SimpleLbObserver(listener, null), body, this, FragmentEvent.DESTROY_VIEW);
    }


    private void bindEmpty() {
        mOrderBeanList.clear();
        mAdapterOrderList.setNewData(mOrderBeanList);

        mNoData = true;
        onRefresh();
    }

    @Override
    public void sendRequestForPageData() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                excuteOrderList(response);
            }
        };
        //售后订单标志(0：非售后订单 1：售后订单 默认0)
        int symbol = 0;
        if (mOrderTypeBean.getTypeCode() == AppConstant.ORDER_STATUS_AFTER_SALE_REC) {
            symbol = 1;
        }
        ApiMethodGuide.getOrderRecList(new SimpleLbObserver(listener, otherListener), mOrderTypeBean.getTypeCode(), symbol, pageNum, pageSize, this, FragmentEvent.DESTROY_VIEW);
    }

    private void excuteOrderList(BaseResponse response) {
        if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
            curPageBean = JsonUtil.getPageBeanFromMap(response.getReturnContent());
            JsonArray jsonOrders = curPageBean.getList();
            if (jsonOrders.size() != 0) {
                for (JsonElement obj : jsonOrders) {
                    OrderListRecBean bean = JsonUtil.getGson().fromJson(obj, OrderListRecBean.class);
                    mOrderBeanList.add(bean);
                }
                mAdapterOrderList.setNewData(mOrderBeanList);
            } else {
                bindEmpty();
            }
            finishRefresh();
        }
    }

//    @Override
//    public void onSupportVisible() {
//        super.onSupportVisible();

//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshOrders(SendGoodsEvent event) {
        if (mUserConfigManager != null) {
            mOrderBeanList = new ArrayList<>();
            sendRequestForPageData();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshOrders(OrderChangeEvent event) {
        if (mUserConfigManager != null) {
            mOrderBeanList = new ArrayList<>();
            sendRequestForPageData();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshOrders(CloseOrderEvent event) {
        if (mUserConfigManager != null) {
            mOrderBeanList = new ArrayList<>();
            sendRequestForPageData();
        }
    }

    public void refresh() {
        mOrderBeanList = new ArrayList<>();
        super.refresh();
    }

    @Override
    public void onRefresh() {
        mAdapterOrderList.setEnableLoadMore(false);
        if (mError) {
            mAdapterOrderList.setEmptyView(errorView);
            mError = false;
        } else {
            if (mNoData) {
                mAdapterOrderList.setEmptyView(noDataView);
                mNoData = false;
            } else {
                refresh();
            }
        }
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (curPageBean == null && mOrderTypeBean != null) {
            sendRequestForPageData();
        }
    }

    @Override
    public void onLoadMoreRequested() {
        if (curPageBean.isHasNextPage()) {
            loadMore();
        } else {
            if (getUserVisibleHint()) {
                ToastUtils.showShort("没有更多了");
            }
            mAdapterOrderList.loadMoreEnd(true);
        }
    }

//    private AdapterOrderList.OnActionClickListener mOnActionClickListener = new AdapterOrderList.OnActionClickListener() {
//        @Override
//        public void onCheckDelivery(OrderListRecBean bean) {
//            if (AppConfigManager.getAppconfigManager(mContext).getDevMode() == AppConstant.KEY_RUN_MODE_FORMAL) {
//                ((FragmentOrderManager) getParentFragment()).start(FragmentCheckDelivery.newInstance("https://singlepage.storeer.com/v2/express?orderNum=" + bean.getOrderNum()));
//            } else {
//                ((FragmentOrderManager) getParentFragment()).start(FragmentCheckDelivery.newInstance("http://192.168.1.102:8088/v2/express?orderNum=" + bean.getOrderNum()));
//            }
//
//        }
//
//        @Override
//        public void onSendGoods(OrderListRecBean bean) {
//            ((FragmentOrderManager) getParentFragment()).start(FragmentSendGoods.newInstance(bean.getOrderNum()));
//        }
//
//        @Override
//        public void closeOrder(final OrderListRecBean bean) {
//            DialogMakeSure dialog = new DialogMakeSure(mContext);
//            dialog.getDialog("是否关闭该订单?").show();
//            dialog.setOnDialogClickListener(new DialogMakeSure.OnDialogClickListener() {
//                @Override
//                public void onSure(DialogInterface dialog, int which) {
//                    sendRequestCloseOrder(bean.getOrderNum());
//                }
//
//                @Override
//                public void onCancel(DialogInterface dialog, int which) {
//                }
//            });
//
//        }
//
//        @Override
//        public void onItemClick(OrderListRecBean bean) {
//            if (mFlag) {
//                if (bean.isStaffOrder()) {
//                    start(FragmentOrderDetail.newInstance(bean.getOrderNum(), AppConstant.FROM_MAIN_ACTIVITY));
//                } else {
//                    ToastUtils.showShort("你无权查看该订单详情");
//                }
//            } else {
//                ((FragmentOrderManager) getParentFragment()).start(FragmentOrderDetail.newInstance(bean.getOrderNum(), AppConstant.FROM_MAIN_ACTIVITY));
//            }
//        }
//
//        @Override
//        public void changePrice(OrderListRecBean bean) {
//            ((FragmentOrderManager) getParentFragment()).start(FragmentChangePrice.newInstance(bean.getOrderDetailList()));
//        }
//    };

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
